package com.uzai.console.web.turnlink;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.uzai.common.enums.PlatformTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.console.common.SelectVo;
import com.uzai.console.dto.turnlink.*;
import com.uzai.console.service.turnlink.TurnLinkService;
import com.uzai.console.vo.turnlink.TurnLinkGenerateVo;
import com.uzai.console.vo.turnlink.TurnLinkGoodsAnalyzeVo;
import com.uzai.console.vo.turnlink.TurnLinkLeagueSettingVo;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 转链控制器接口
 *
 * @author mingyang.chen create in 2022/11/3 14:26
 */
@Api(value = "转链相关的接口", tags = "转链")
@RestController
@RequestMapping("/turnLink")
@Slf4j
public class TurnLinkController extends BaseController {

    @Autowired
    private TurnLinkService turnLinkService;

    /**
     * Analyze goods object.
     *
     * @param goodsAnalyze the goods analyze
     * @return the object
     */
    @ApiOperation(value = "转链内容解析", response = TurnLinkGoodsAnalyzeVo.class)
    @PostMapping("/analyze")
    public Object analyzeGoods(@RequestBody TurnLinkGoodsAnalyzeDto goodsAnalyze) {

        log.info("analyzeGoods is execute, param: {}", JSON.toJSONString(goodsAnalyze));
        if (Objects.isNull(goodsAnalyze) || StringUtils.isAnyBlank(goodsAnalyze.getContent())) {
            throw new BusinessException("转链内容解析参数错误");
        }
        TurnLinkGoodsAnalyzeVo analyzeGoods = turnLinkService.analyzeGoods(goodsAnalyze);
        log.info("analyzeGoods is end, result: {}", analyzeGoods);
        return analyzeGoods;
    }

    /**
     * Generate object.
     *
     * @param generateDto the generate dto
     * @return the object
     */
    @ApiOperation(value = "生成转链", response = TurnLinkGenerateVo.class)
    @PostMapping("/generate")
    public Object generate(@RequestBody TurnLinkGenerateDto generateDto) {
        log.info("generate is execute, param: {}", JSON.toJSONString(generateDto));
        if (Objects.isNull(generateDto) || Objects.isNull(generateDto.getPlatform())
                || Objects.isNull(generateDto.getSettingId())) {
            throw new BusinessException("转链生成参数错误");
        }
        String goodsId = generateDto.getGoodsId();
        List<String> goodsIds = ObjectUtils.defaultIfNull(generateDto.getGoodsIds(), Lists.newArrayList());
        if (StringUtils.isNotBlank(goodsId) && !goodsIds.contains(goodsId)) {
            goodsIds.add(goodsId);
        }
        List<TurnLinkGenerateVo> turnLinkGenerateVoMap = new ArrayList<>();

        for (String goodsIdItem : goodsIds) {
            generateDto.setGoodsId(goodsIdItem);
            TurnLinkGenerateVo generateVo = turnLinkService.turnLink(generateDto);
            turnLinkGenerateVoMap.add(generateVo);
        }
        log.info("generate is end, result: {}", JSON.toJSONString(turnLinkGenerateVoMap));
        return turnLinkGenerateVoMap;
    }

    @ApiOperation(value = "转链活动生成转链", response = TurnLinkGenerateVo.class)
    @PostMapping("/activity/generate")
    public Object activityGenerate(@RequestBody TurnLinkGenerateDto generateDto) {
        log.info("activityGenerate is execute, param: {}", JSON.toJSONString(generateDto));
        if (Objects.isNull(generateDto) || Objects.isNull(generateDto.getPlatform()) || ObjectUtils.anyNull(generateDto.getSettingId(), generateDto.getTokenId())) {
            throw new BusinessException("活动转链生成参数错误");
        }
        if (Objects.equals(generateDto.getPlatform(), PlatformTypeEnum.PT_TAOBAO.getId()) && StringUtils.isAnyBlank(generateDto.getActivityId())) {
            throw new BusinessException("活动id必填");
        }
        if (Objects.equals(generateDto.getPlatform(), PlatformTypeEnum.PT_JD.getId()) && StringUtils.isAnyBlank(generateDto.getActivityLink())) {
            throw new BusinessException("活动链接必填");
        }
        if (Objects.equals(generateDto.getPlatform(), PlatformTypeEnum.PT_VPH.getId()) && StringUtils.isAnyBlank(generateDto.getActivityLink())) {
            throw new BusinessException("活动链接必填");
        }
        TurnLinkGenerateVo generateVo = turnLinkService.activityTurnLink(generateDto);
        log.info("activityGenerate is end, result: {}", generateVo);
        return generateVo;
    }

    @ApiOperation(value = "转链活动下拉接口", response = SelectVo.class)
    @PostMapping("/activity/select")
    public Object activitySelect() {
        return turnLinkService.listMarketingActivity();
    }

    @ApiOperation(value = "生成短链接", response = String.class)
    @PostMapping("/generate/short")
    public Object generateShortLink(@RequestBody TurnShortLinkDto shortLinkDto) {
        log.info("generateShortLink is execute, param: {}", JSON.toJSONString(shortLinkDto));
        if (Objects.isNull(shortLinkDto) || Objects.isNull(shortLinkDto.getMerId())) {
            throw new BusinessException("短链接生成参数错误");
        }
        String link = shortLinkDto.getLink();
        List<String> links = ObjectUtils.defaultIfNull(shortLinkDto.getLinks(), Lists.newArrayList());
        if (StringUtils.isNotBlank(link) && !links.contains(link)) {
            links.add(link);
        }
        List<String> shortLinks = new ArrayList<>();
        for (String linkItem : links) {
            String generateVo = turnLinkService.generateShortLink(linkItem, shortLinkDto.getMerId());
            shortLinks.add(generateVo);
        }
        log.info("generateShortLink is end, result: {}", JSON.toJSONString(shortLinks));
        return shortLinks;
    }

    /**
     * Gets turn link league setting by platform.
     *
     * @param settingQuery the setting query
     * @return the turn link league setting by platform
     */
    @ApiOperation(value = "各个平台转链联盟配置获取接口", response = TurnLinkLeagueSettingVo.class)
    @PostMapping(value = "/leagueSetting/getByPlatform")
    public Object getTurnLinkLeagueSettingByPlatform(@RequestBody TurnLinkLeagueSettingQuery settingQuery) {

        log.info("getTurnLinkLeagueSetting is execute, param: {}", JSON.toJSONString(settingQuery));

        if (Objects.isNull(settingQuery) || Objects.isNull(settingQuery.getPlatform())) {
            throw new BusinessException("转链联盟配置获取参数错误");
        }
        TurnLinkLeagueSettingVo settingVos = turnLinkService.getTurnLinkLeagueSettingByPlatform(settingQuery.getMerId(), settingQuery.getPlatform());
        log.info("getTurnLinkLeagueSetting is end, result: {}", settingVos);
        return settingVos;
    }

    /**
     * Gets turn link league setting.
     *
     * @return the turn link league setting
     */
    @ApiOperation(value = "所有平台转链联盟配置获取接口", response = TurnLinkLeagueSettingVo.class)
    @PostMapping(value = "/leagueSetting/get")
    public Object getTurnLinkLeagueSetting() {

        Long merId = super.getLoginInfo().getMerId();
        log.info("getTurnLinkLeagueSetting is execute, merId: {}", merId);

        if (Objects.isNull(merId)) {
            throw new BusinessException("转链联盟配置获取参数错误");
        }
        List<TurnLinkLeagueSettingVo> settingVos = turnLinkService.getTurnLinkLeagueSetting(merId);
        log.info("getTurnLinkLeagueSetting is end, result: {}", settingVos);
        return settingVos.stream().collect(Collectors.toMap(TurnLinkLeagueSettingVo::getPlatform, Function.identity()));
    }

    /**
     * Save turn link league setting object.
     *
     * @param param the turn link setting
     * @return the object
     */
    @ApiOperation(value = "联盟配置保存", response = Long.class)
    @PostMapping(value = "/leagueSetting/save")
    public Object saveTurnLinkLeagueSetting(@RequestBody TurnLinkLeagueSettingSaveDto param) {

        if (Objects.isNull(param) || CollectionUtils.isEmpty(param.getSettingList())) {
            throw new BusinessException("转链联盟配置保存参数错误");
        }
        log.info("saveTurnLinkLeagueSetting is execute, param: {}", JSON.toJSONString(param));

        // doCheckSettingsParam(param.getSettingList());

        Long merId = super.getLoginInfo().getMerId();
        List<Long> ids = turnLinkService.saveTurnLinkLeagueSetting(merId, param.getSettingList());
        log.info("saveTurnLinkLeagueSetting is end, result: {}", ids);
        return ids;
    }

    private void doCheckSettingsParam(List<TurnLinkLeagueSettingDto> settingList) {

        for (TurnLinkLeagueSettingDto turnLinkLeagueSettingDto : settingList) {
            Integer platform = turnLinkLeagueSettingDto.getPlatform();
            if (Objects.isNull(platform)) {
                throw new BusinessException("平台参数信息错误");
            }
            if (platform != PlatformTypeEnum.PT_TAOBAO_VALUE && Objects.nonNull(turnLinkLeagueSettingDto.getExt()) && !turnLinkLeagueSettingDto.getExt().isEmpty()) {
                throw new BusinessException("扩展参数仅支持淘宝平台!");
            }

            List<TurnLinkLeagueSettingDto.TurnLinkLeagueSettingAccount> relAccounts = turnLinkLeagueSettingDto.getRelAccounts();
            if (ObjectUtils.isEmpty(relAccounts)) {
                return;
            }
            for (TurnLinkLeagueSettingDto.TurnLinkLeagueSettingAccount relAccount : relAccounts) {
                if (platform != PlatformTypeEnum.PT_TAOBAO_VALUE && ObjectUtils.isNotEmpty(relAccount.getPromotion()) && !relAccount.getPromotion().isEmpty()) {
                    throw new BusinessException("推广位参数仅在淘宝平台有效!");
                }
                if (Objects.isNull(relAccount.getAccountId())) {
                    throw new BusinessException("联盟账号参数必填!");
                }
                if (PlatformTypeEnum.PT_PDD_VALUE == platform && Objects.isNull(relAccount.getAccountType())) {
                    throw new BusinessException("拼多多联盟账号类型参数必填!");
                }
            }
        }
    }
}
